# 项目：python_project
# 文件：tools
# 作者：WuTong
# 日期：2025/5/21,09:09
# coding:utf-8
import json
from time import sleep

from selenium import webdriver
from selenium.webdriver.support.select import Select


class UIAction:

    driver = None

    @classmethod
    def get_driver(cls):
        if cls.driver is None:   # 单例模式
            cls.driver = webdriver.Edge() # 使用Edge浏览器
            cls.driver.implicitly_wait(5) # 隐式等待5秒
            cls.driver.maximize_window() # 窗口最大化
        return cls.driver

    @classmethod
    def write(cls,element,value):
        """
        定位文本框元素，先点击再清空文本框，最后输入新的值
        :param element: 定位方式
        :param value: 定位值
        :return: 无返回值
        """
        element.click()
        element.clear()
        element.send_keys(value)

    @classmethod
    def is_element_present(cls, by, value):
        """
        判断某个元素是否存在，返回真或假的结果
        :param by: 定位方式
        :param value: 定位值
        :return: True or False
        """
        try:
            cls.driver.find_element(by, value)
            return True
        except Exception as e:
            return False

    @classmethod
    def select_random(cls,element):
        import random
        random_index = random.randint(1, len(Select(element).options) - 1)
        Select(element).select_by_index(random_index)

    @classmethod
    def do_login(cls):
        """
        以管理员身份登录系统
        :return: 无返回值
        """
        driver = cls.driver
        login_info = Util.read_json('../datas/conf.json')['login_info']
        driver.get('http://localhost:8080/YunDuanBoss/login/')
        uname = driver.find_element('name', 'userName')
        cls.write(uname, login_info['uname'])
        upass = driver.find_element('name', 'userPass')
        cls.write(upass, login_info['upass'])
        driver.find_element('css selector','#form-login >'
                                           ' div > div > div.modal-footer > button').click()
        sleep(5)



class Util:
    @classmethod
    def get_conn(cls):
        """
        链接数据库
        :return: 无
        """
        import pymysql
        db_info = cls.read_json('conf.json')['appdb']
        return pymysql.connect(**db_info, charset='utf8')

    @classmethod
    def query(cls, sql):
        conn = cls.get_conn()
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result

    @classmethod
    def update(cls, sql):
        conn = cls.get_conn()
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()

    @classmethod
    def read_json(cls,path):
        """
        用于读取指定的json文件，返回json格式的数据
        :param path: json文件的路径和名称
        :return: json格式的数据
        """
        with open(path,encoding='utf8') as file:
            contents = json.load(file)
        return contents

    @classmethod
    def read_txt(cls,path):
        with open(path,encoding='utf8') as file:
            contents = file.readlines()
        li = []
        for content in contents:
            if content != '\n' and not content.startswith('# '):
                if "# " in content.strip():
                    li.append(content.strip().split('# ')[0].strip())
                else:
                    li.append(content.strip())
        return li

    @classmethod
    def read_ini(cls, section):
        with open('../datas/elements.ini', encoding='utf8') as file:
            contents = file.read()
        all = contents.split('[ ')
        result = {}
        for item in all:
            if item.startswith(section):
                temp = item.split(' ]')[1].strip()
                items = temp.split('\n')
                for it in items:
                    if not it.startswith('# ') and it != '\n':
                        value = it.split(' = ')[1]
                        if '# ' in value:
                            value1 = value.split('# ')[0].strip()
                            result[it.split(' = ')[0]] = value1
                        else:
                            result[it.split(' = ')[0]] = value
        return result

    @classmethod
    def get_ini_value(cls, section, option):
        result = cls.read_ini(section)
        return eval(result[option])

    @classmethod
    def read_excel(cls,**kwargs):
        import xlrd
        workbook = xlrd.open_workbook('../datas/testdata.xls')
        sheet = workbook.sheet_by_name(kwargs['sheetname'])
        li = []
        for i in range(kwargs['starrow'],kwargs['endrow']):
            data = sheet.cell(i,kwargs['data_col']).value
            info = {}
            di = {}
            temp = str(data).split('\n')
            for t in temp:
                di[t.split('=')[0]] = t.split('=')[1]
            info['data'] = di
            info['expect'] = sheet.cell(i,kwargs['expect_col']).value
            li.append(info)
        return li

    @classmethod
    def get_info(cls,casename):
        caseinfo = Util.read_json('../datas/conf.json')[casename]
        return Util.read_excel(**caseinfo)


class Assert:

    @classmethod
    def assert_equal(cls,expect, actual):
        if expect == actual:
            print('test pass')
        else:
            print('test fail')

    @classmethod
    def assert_not_equal(cls, expect, actual):
        if expect != actual:
            print('test pass')
        else:
            print('test fail')

    @classmethod
    def assert_contain(cls,expect, actual):
        if actual in expect:
            print('test pass')
        else:
            print('test fail')

if __name__ == '__main__':
    pass
